package cn.bouncyslime.algorithms.tree.binaryTree;

/*
* 根据输入的数组构建二叉树，并进行二叉树的先序遍历，中序遍历和后序遍历
*
*
* */

public class BinaryTree {

    // 从数组中读取数据，构建二叉树
    public TreeNode createTree(int[] array){
        TreeNode root;
        if (array==null || array.length==0){
            root = null;
        }else {
            root = new TreeNode(array[0]);
            createBinaryTree(root, array, 0);
        }
        return root;
    }

    public void createBinaryTree(TreeNode node, int[] array, int position){
        if(node.getLeft()==null && array.length>2*position+1 && array[2*position+1]!=0){
            node.setLeft(new TreeNode(array[2*position+1]));
            createBinaryTree(node.getLeft(), array, 2*position+1);
        }
        if(node.getRight()==null && array.length>2*position+2 && array[2*position+2]!=0){
            node.setRight(new TreeNode(array[2*position+2]));
            createBinaryTree(node.getRight(), array, 2*position+2);
        }
    }

    public static void main(String[] args){
        BinaryTree bt = new BinaryTree();

        int[] array = {1,2,3,4,5,0,0,0,0,6,7};

        TreeNode root = bt.createTree(array);

        System.out.println("层次遍历二叉树");
        Traversal_Hierarchical th = new Traversal_Hierarchical();
        th.traverse(root);

        System.out.println("先序遍历（DLR）_递归");
        Traversal_DLR t_DLR = new Traversal_DLR();
        t_DLR.recurse(root);
        System.out.println("\n先序遍历（DLR）_迭代");
        t_DLR.iterate(root);

        System.out.println("中序遍历（LDR）_递归");
        Traversal_LDR t_LDR = new Traversal_LDR();
        t_LDR.recurse(root);
        System.out.println("\n中序遍历（LDR）_迭代");
        t_LDR.iterate(root);

        System.out.println("后序遍历（LRD）_递归");
        Traversal_LRD t_LRD = new Traversal_LRD();
        t_LRD.recurse(root);
        System.out.println("\n后序遍历（LRD）_迭代");
        t_LRD.iterate(root);
    }
}